import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Image } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import * as SecureStore from 'expo-secure-store';
import { useRouter } from 'expo-router';
import { clearGiftRewards } from '@/store/giftRewardSlice';
import { RootState } from '@/store/paystore';


export default function Consumer() {
    const dispatch = useDispatch();
    const router = useRouter();
    const [giftRewards, setGiftRewards] = useState<any[]>([]);
    const reduxGiftRewards = useSelector((state: RootState) => state.giftReward.giftRewards);
    useEffect(() => {
        const loadGiftRewards = async () => {
            try {
                const giftRewards = await SecureStore.getItemAsync('giftRewards');
                if (giftRewards) {
                    const parsedRewards = JSON.parse(giftRewards);
                    console.log(parsedRewards, 'parsedRewards');
                    // 通过 Redux 初始化 giftRewards 数据
                    setGiftRewards(parsedRewards);
                }
            } catch (error) {
                console.error('Error loading giftRewards from SecureStore:', error);
            }
        };
        loadGiftRewards()
    }, [dispatch]);



    const formatTime = (isoTime) => {
        const date = new Date(isoTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
    };

    useEffect(() => {
        // 当 Redux 中的 giftRewards 更新时，更新组件内部的状态
        setGiftRewards(reduxGiftRewards);
    }, [reduxGiftRewards]);

    return (
        <View style={styles.container}>
            <View style={styles.headerLeft}>
                <TouchableOpacity onPress={() => router.back()}>
                    <Image source={require('../../assets/images/back.png')} style={styles.headerImg} />
                </TouchableOpacity>
                <Text style={styles.title}>消费明细</Text>
                <Text style={styles.title}></Text>
            </View>
            {giftRewards.length > 0 ? (
                <View>
                    <FlatList
                        data={giftRewards}
                        keyExtractor={(item) => item.id} // 使用订单 ID 作为唯一 key
                        renderItem={({ item }) => (
                            <View style={styles.orderContainer} key={item.id}>
                                <View style={styles.priceContainer}>
                                </View>
                                <Text style={styles.orderText}>支付金额: ¥{item.diamonds}</Text>
                                <Text style={styles.orderText}>支付时间: {formatTime(item.time)}</Text>
                            </View>
                        )}
                    />
                    <Text style={styles.clearData} onPress={() => {
                        dispatch(clearGiftRewards());
                    }}>清除数据</Text>
                </View>

            ) : (
                <Text style={styles.noOrders}>暂无数据</Text>
            )
            }
        </View >
    );
}

const styles = StyleSheet.create({
    clearData: {
        marginLeft: 250,
        marginTop: 10,
        color: 'red'
    },
    priceContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginRight: -40,
    },
    diamondImg: {
        width: 20,
        height: 20,
        marginLeft: 5,
        marginTop: 5,
    },
    headerImg: {
        width: 20,
        height: 20,
    },
    headerLeft: {
        marginTop: 12,
        display: 'flex',
        alignItems: 'center',
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    container: {
        flex: 1,
        padding: 20,
        backgroundColor: '#fff',
    },
    title: {
        fontSize: 16,
        fontWeight: 'bold',
    },
    orderContainer: {
        marginBottom: 10,
        padding: 15,
        borderWidth: 1,
        borderColor: '#ddd',
        borderRadius: 8,
        backgroundColor: '#f9f9f9',
        marginTop: 20,
    },
    orderText: {
        fontSize: 16,
        marginTop: 5
    },
    noOrders: {
        fontSize: 15,
        color: 'black',
        textAlign: 'center',
        marginTop: 20,
        marginLeft: 10
    },
});
